<script setup lang="ts">
import TagView from "@/components/tagview/TagView.vue";
import {onBeforeRouteUpdate, useRoute, useRouter} from "vue-router";
import pinia from "@/stores";
import {useTagViewState} from "@/stores/tagview/tagViewState";

const tagViewState = useTagViewState(pinia)
const route = useRoute()
const router = useRouter()
setTagView(route)
function setTagView(route:any){
  let name = route.meta.title
  let key = route.name
  const tagName = route.query.tagName
  if (tagName){
    name = tagName
    key = `${route.name}-${tagName}`
  }
  const isExist = tagViewState.getTagViews().some(item => item.key === key)
  if (!isExist){
    tagViewState.addTagView({
      name: name,
      path: route.path,
      key: key,
      icon: route.meta.icon,
      query: route.query
    })
  }
}
onBeforeRouteUpdate((to) => {
  setTagView(to)
})

const onClose = (item:any) => {
  const index = tagViewState.delTagView(item.key)
  if (item.key == route.name){
    let selectIndex = index;
    if (index !== 0){
      selectIndex = index -1;
    }
    const beforeTagView = tagViewState.getTagViews()[selectIndex]
    router.push({
      path: beforeTagView.path,
      query: beforeTagView.query
    })
  }
}
</script>
<template>
  <el-scrollbar class="tag-views">
    <tag-view :label="item.name"
              :key="item.key"
              :key-id="item.key"
              :route="item.path"
              :closed="tagViewState.showClose"
              :is-active="(route.query.tagName?`${String(route.name)}-${route.query.tagName}`:route.name) == item.key"
              :icon="item.icon"
              :query="item.query"
              v-for="item in tagViewState.tagViewList"
              @close="onClose(item)" />
  </el-scrollbar>
</template>
<style scoped>
.el-scrollbar{
  height: unset;
}
.tag-views{
  padding: 8px 20px;
}
</style>